<template>
  <base-modal class="service-dialog-container" :title="$t('common.base.add2')" :show.sync="visible" width="700px" @closed="handleClose">
    <div class="rules-main">
      <el-form ref="ruleForm" :model="ruleForm" inline>
        <div class="form-item-box" v-for="(item, index) in ruleForm.discountRulesList" :key="item.id">
          <el-form-item>
            <span>{{ $t('kaili.tip.serviceItems') }}：</span>
          </el-form-item>
          <el-form-item>
            <span>{{ $t('kaili.tip.article') }}</span>
          </el-form-item>
          <el-form-item :prop="`discountRulesList.${index}.row`">
            <el-input v-model="item.row" disabled></el-input>
          </el-form-item>
          <el-form-item>
            <span>{{ $t('kaili.tip.row') }}</span>
          </el-form-item>
          <el-form-item>
            <span>{{ $t('kaili.tip.discount') }}：</span>
          </el-form-item>
          <el-form-item :prop="`discountRulesList.${index}.index`">
            <el-input v-model="item.index" maxlength="5" @input="handleInput(item, 'index')"></el-input>
          </el-form-item>
          <el-form-item>
            <span>%</span>
          </el-form-item>
          <el-form-item>
            <el-button class="delete-btn" icon="iconfont icon-delete" @click="handleDelAndItem(item)"></el-button>
          </el-form-item>
        </div>
      </el-form>
      <div class="tips">{{ $t('kaili.tip.tips3') }}</div>
      <el-button size="small" @click="handleAddItem"> {{ $t('common.base.add2') }}</el-button>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="resetForm('ruleForm')">{{ $t('common.base.cancel') }}</el-button>
      <el-button type="primary" @click="submitForm('ruleForm')">{{ $t('common.base.submit') }}</el-button>
    </div>
  </base-modal>
</template>

<script>
/* util */
import { debounce, cloneDeep } from 'lodash';
import { uuid } from 'pub-bbx-utils';
/* model */
import { PART_SERVICE_LIST_PRENUM_MAX_LENGTH } from '@src/model/const/Number';
export default {
  name: 'discount-rules',
  props:{
    field:{
      type:Object,
      default:() => ({})
    }
  },
  data() {
    return {
      visible: false,
      ruleForm: {
        discountRulesList: [],
      },
    };
  },
  watch:{
    field:{
      handler(){
        this.resetDiscountRules()
      },
      immediate: true,
    }
  },
  computed: {},
  methods: {
    resetDiscountRules(){
      let defaultRuleData = [
        { id: uuid(), row: '1', index: '0' },
        { id: uuid(), row: '2', index: '30' },
        { id: uuid(), row: '3', index: '50' },
      ]
      if(this.field.setting.hasOwnProperty('serviceItemDiscountSettings')){
        defaultRuleData = this.field?.setting?.serviceItemDiscountSettings || []
      }
      this.ruleForm.discountRulesList = cloneDeep(defaultRuleData);
    },
    handleClose(){
      this.resetDiscountRules()
    },
    handleInput(item, type) {
      this.dbInputHandle(item, type);
    },
    dbInputHandle: debounce(function (item, type) {
      // 去掉字符串中的所有非数字和点号
      let value = item[type].replace(/[^\d.]/g, '');

      // 如果有多个小数点，则只保留第一个
      let arr = value.split('.');
      if (arr.length > 2) {
        value = arr[0] + '.' + arr.slice(1).join('');
      }

      // 如果小数部分超过了两位，则截取前两位
      if (arr.length === 2 && arr[1].length > 2) {
        value = arr[0] + '.' + arr[1].substring(0, 2);
      }

      // 如果开头是零，则去掉开头的零
      if (value.startsWith('0') && value.length > 1 && !value.startsWith('0.')) {
        value = value.substring(1);
      }

      // 更新输入框的值
      value > 100 ? (item[type] = '0') : (item[type] = value);
    }, 500),
    handleAddItem() {
      const obj = { id: uuid(), row: this.ruleForm.discountRulesList.length + 1, index: '' };
      const max = PART_SERVICE_LIST_PRENUM_MAX_LENGTH;
      if (this.ruleForm.discountRulesList.length >= max) return this.$message.warning(this.$t('formSetting.subFormApi.maxAdd',{max}));
      this.ruleForm.discountRulesList.push(obj);
    },
    handleDelAndItem(item) {
      this.ruleForm.discountRulesList = this.ruleForm.discountRulesList.filter(val => val.id !== item.id).map((val, index) => {
        val.row = index + 1
        return val
      });
    },
    submitForm() {
      const blankItems = this.ruleForm.discountRulesList.some(item => !item.row || (item.row && !item.index));
      if (blankItems) return this.$message.warning(this.$t('common.base.tip.cantHaveNullOption'));

      const numData = this.ruleForm.discountRulesList.map(item => item.row);
      if (new Set(numData).size !== numData.length) return this.$message.warning(this.$t('common.base.repeateIsNotAllow'));

      this.$emit('submit', this.ruleForm.discountRulesList);
      this.visible = false;
    },
    resetForm() {
      this.visible = false;
    },
    // 打开添加服务项目折扣规则弹窗
    open() {
      this.visible = true;
    },
  },
};
</script>

<style lang="scss" scoped>
.el-form {
  .form-item-box {
    display: flex;
    // justify-content:space-around;
    align-items: center;
    margin-bottom: 20px;
    .el-form-item {
      margin: 0;
      ::v-deep .el-form-item__content {
        .el-input {
          .el-input__inner {
            width: 100px;
            margin: 0 10px;
          }
        }
        .el-form-item__error {
          margin: 0 10px;
        }
      }
      .delete-btn {
        margin-left: 10px;
      }
    }
  }
  .el-button {
    ::v-deep i {
      font-size: 14px;
      margin: 0px !important;
    }
  }
}
.rules-main {
  box-sizing: border-box;
  padding: 16px;
  height: 500px;
  overflow: auto;
  .tips {
    margin-bottom: 10px;
    color: #ff9100;
  }
}
</style>
